import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginForm, LoginResponse, UserForm } from '@/types'
import { login, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '')
  const user = ref<User | null>(null)
  const permissions = ref<string[]>([])
  const menus = ref<any[]>([])

  // 用户管理数据
  const users = ref<User[]>([
    {
      id: 1,
      username: 'admin',
      nickname: '系统管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      status: 'active',
      roles: ['admin'],
      departmentId: 1,
      departmentName: '裸眼电缆作业中心',
      employeeNumber: 'EMP001',
      position: '系统管理员',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 2,
      username: 'manager001',
      nickname: '张经理',
      email: 'zhang.manager@example.com',
      phone: '13800138001',
      status: 'active',
      roles: ['manager', 'area_manager'],
      departmentId: 1,
      departmentName: '裸眼电缆作业中心',
      employeeNumber: 'EMP002',
      position: '部门经理',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 3,
      username: 'authority002',
      nickname: '李工程师',
      email: 'li.engineer@example.com',
      phone: '13800138002',
      status: 'active',
      roles: ['authority_level_2'],
      departmentId: 2,
      departmentName: '随钻测量作业中心',
      employeeNumber: 'EMP003',
      position: '高级工程师',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 4,
      username: 'approver003',
      nickname: '王主任',
      email: 'wang.director@example.com',
      phone: '13800138003',
      status: 'active',
      roles: ['approver_level_3'],
      departmentId: 3,
      departmentName: '装备技术中心',
      employeeNumber: 'EMP004',
      position: '技术主任',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 5,
      username: 'safety001',
      nickname: '刘监督',
      email: 'liu.supervisor@example.com',
      phone: '13800138004',
      status: 'active',
      roles: ['safety_supervisor'],
      departmentId: 1,
      departmentName: '裸眼电缆作业中心',
      employeeNumber: 'EMP005',
      position: '安全监督',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 6,
      username: 'contractor001',
      nickname: '赵师傅',
      email: 'zhao.master@contractor.com',
      phone: '13800138005',
      status: 'active',
      roles: ['operation_manager'],
      contractorId: 1,
      contractorName: '中海油服钻井技术有限公司',
      employeeNumber: 'CON001',
      position: '作业负责人',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    }
  ])

  const isLoggedIn = computed(() => !!token.value)

  // 初始化用户信息（用于刷新后恢复状态）
  const initializeUser = async () => {
    if (token.value && !user.value) {
      try {
        await getUserInfoAction()
      } catch (error) {
        console.error('Failed to initialize user:', error)
        // 如果获取用户信息失败，清除无效的token
        logout()
      }
    }
  }

  // 登录
  const loginAction = async (loginForm: LoginForm) => {
    try {
      // 演示模式：模拟登录成功
      const mockResponse = {
        token: 'demo-token-' + Date.now(),
        user: {
          id: 1,
          username: loginForm.username,
          nickname: loginForm.username === 'admin' ? '系统管理员' : '普通用户',
          avatar: '',
          email: 'demo@example.com',
          phone: '13800138000',
          roles: loginForm.username === 'admin' ? ['admin', 'manager'] : ['user'],
          department: loginForm.username === 'admin' ? '管理部' : '生产部'
        },
        permissions: loginForm.username === 'admin' ? ['*'] : ['read'],
        menus: []
      }
      
      token.value = mockResponse.token
      user.value = mockResponse.user
      permissions.value = mockResponse.permissions
      menus.value = mockResponse.menus
      
      localStorage.setItem('token', mockResponse.token)
      return mockResponse
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      // 演示模式：返回模拟用户信息
      const mockResponse = {
        user: {
          id: 1,
          username: 'admin',
          nickname: '系统管理员',
          avatar: '',
          email: 'demo@example.com',
          phone: '13800138000',
          roles: ['admin', 'manager'],
          department: '管理部'
        },
        permissions: ['*'],
        menus: []
      }
      
      user.value = mockResponse.user
      permissions.value = mockResponse.permissions
      menus.value = mockResponse.menus
      return mockResponse
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    permissions.value = []
    menus.value = []
    localStorage.removeItem('token')
  }

  // 检查权限
  const hasPermission = (permission: string) => {
    return permissions.value.includes(permission)
  }

  // 用户管理相关方法
  const getAllUsers = () => {
    return Promise.resolve(users.value)
  }

  const getUserById = (id: number) => {
    const foundUser = users.value.find(u => u.id === id)
    return Promise.resolve(foundUser)
  }

  const createUser = (form: UserForm) => {
    const newUser: User = {
      id: Math.max(...users.value.map(u => u.id)) + 1,
      ...form,
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    users.value.push(newUser)
    return Promise.resolve(newUser)
  }

  const updateUser = (id: number, form: UserForm) => {
    const index = users.value.findIndex(u => u.id === id)
    if (index !== -1) {
      users.value[index] = {
        ...users.value[index],
        ...form,
        updateTime: new Date().toLocaleString()
      }
      return Promise.resolve(users.value[index])
    }
    return Promise.reject(new Error('用户不存在'))
  }

  const deleteUser = (id: number) => {
    const index = users.value.findIndex(u => u.id === id)
    if (index !== -1) {
      users.value.splice(index, 1)
      return Promise.resolve(true)
    }
    return Promise.reject(new Error('用户不存在'))
  }

  const getUsersByDepartment = (departmentId: number) => {
    const filtered = users.value.filter(u => u.departmentId === departmentId)
    return Promise.resolve(filtered)
  }

  const getUsersByContractor = (contractorId: number) => {
    const filtered = users.value.filter(u => u.contractorId === contractorId)
    return Promise.resolve(filtered)
  }

  const getUsersByRole = (role: string) => {
    const filtered = users.value.filter(u => u.roles.includes(role))
    return Promise.resolve(filtered)
  }

  return {
    token,
    user,
    permissions,
    menus,
    users,
    isLoggedIn,
    loginAction,
    getUserInfoAction,
    logout,
    hasPermission,
    initializeUser,
    // 用户管理方法
    getAllUsers,
    getUserById,
    createUser,
    updateUser,
    deleteUser,
    getUsersByDepartment,
    getUsersByContractor,
    getUsersByRole
  }
})
